package com.sq.goodline.service;

import java.io.File;
import java.util.Date;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sq.goodline.config.ApiConfig;
import com.sq.goodline.dao.AudioDetailDao;
import com.sq.goodline.dao.AudioDownloadDao;
import com.sq.goodline.dao.po.AudioDetail;
import com.sq.goodline.dao.po.AudioDownload;
import com.sq.goodline.util.DateUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class FileService {
	
	@Autowired
	ApiConfig apiConfig;
	@Autowired
	AudioDetailDao audioDetailDao;
	@Autowired
	OssService ossService ;
	@Autowired
	RecToWavService recToWavService;
	@Autowired
	SshService sshService;
	@Autowired
	AudioDownloadDao audioDownloadDao ;
	/**
	 * 下载录音URL
	 * @param flowno
	 * @param sign
	 * @param format文件格式：支持rec\wav\mp3
	 * @return
	 */
	public ResponseEntity<Resource> downloadFile(String flowno, String sign,String format) {
		boolean isDown=false;
		long fileSize = 0;
		try {
			log.info("下载录音文件flowno:{},sign:{},format:{}",flowno,sign,format);
			//签名校验
			if(!checkSign(flowno, sign)) {
				return ResponseEntity.badRequest().build();
			}
			String contentType=getContentType(format);
			if(format!=null&&contentType==null) {
				log.info("不支持的录音格式：{}",format);
				return ResponseEntity.badRequest().build();
			}
			
			AudioDetail audioDetail = audioDetailDao.selectById(flowno);
			if(audioDetail==null) {
				log.info("未找到话单录音记录，flowno：{}",flowno);
				return ResponseEntity.badRequest().build();
			}
			
			Date d = DateUtils.format(DateUtils.currentDate());
			QueryWrapper<AudioDownload> qw = new QueryWrapper<>();
			qw.eq("down_flowno", flowno); 
			qw.gt("down_time", d);//大于yyyy-mm-dd
			
			Integer cnt = audioDownloadDao.selectCount(qw);
			if(cnt>5) {
				log.info("当天下载次数超限，flowno：{}",flowno);
				return ResponseEntity.badRequest().build();
			}
			
			//下载的文件名
			String downFileName = flowno+"."+format;
			File recLocalFile = new File(apiConfig.getDownFileTempPath()+downFileName);
			if(recLocalFile.exists()==false) {//本地不存在此文件，（用户重复下载时，直接拿本地的）
				if(audioDetail.getAudioStatus()==0) {//从VOS服务器拿
					log.info("从VOS服务器238拿rec文件:{}",audioDetail.getRecRecordPath());
					sshService.scpGetFile(audioDetail.getRecRecordPath(), apiConfig.getDownFileTempPath());
					log.info("rec文件已下载到目录：{}",apiConfig.getDownFileTempPath());
					recLocalFile = new File(apiConfig.getDownFileTempPath()+audioDetail.getOriginRecName());//原始文件名
				}else if(audioDetail.getAudioStatus()==1) {//从oss拿
					log.info("从OSS下载rec文件:{}",audioDetail.getRecOssPath());
					recLocalFile = new File(apiConfig.getDownFileTempPath()+flowno+".rec");//重新命名为flowno.rec
					ossService.getFileLocal(audioDetail.getRecOssPath(), recLocalFile);
					log.info("文件从OSS下载到本地完成：{}",recLocalFile.getAbsolutePath());
				}else {
					log.info("暂不支持下载");
					return ResponseEntity.notFound().build();
				}
				
				//原录音格式为rec，如果要下载wav或mp3，需要先转换
				if("wav".equalsIgnoreCase(format) || "mp3".equalsIgnoreCase(format)) {
					String convertFilePath = apiConfig.getDownFileTempPath()+downFileName;
					if(recToWavService.doShellConvert(recLocalFile.getAbsolutePath(), convertFilePath)) {
						recLocalFile= new File(convertFilePath);//转换后的文件
					}else {
						log.info("shell转换失败。");
						return ResponseEntity.badRequest().build();
					}
				} 
			}
			
			fileSize = recLocalFile.length();
			log.info("文件大小：{} byte",fileSize);
			
			Resource resource=new FileSystemResource(recLocalFile);
			HttpHeaders heads = new HttpHeaders();
			heads.add(HttpHeaders.CONTENT_TYPE, contentType);
			heads.add(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\""+downFileName+"\"");
			
			isDown = true;
			
			return ResponseEntity.ok()
					.headers(heads)
					.body(resource);
		}catch(Exception e) {
			log.error("下载异常：",e);
			return ResponseEntity.notFound().build();
		}finally {
			if(isDown) {
				AudioDownload ad = new AudioDownload();
				ad.setDownFlowno(flowno);
				ad.setDownFormat(format);
				ad.setFileSize(fileSize);
				int i = audioDownloadDao.insert(ad);
				log.info("插入下载记录完成：{}",i);
			}
		}
	}

	//md5校验签名
	private boolean checkSign(String flowno, String sign) {
		String mySign = DigestUtils.md5Hex(flowno+apiConfig.getSignSalt());
		if(mySign.equalsIgnoreCase(sign)){
			return true;
		}
		log.info("验签失败，我方签名为："+mySign);
		return false;
	}
	
	// 获取 MIME 类型
    private String getContentType(String format) {
        if ("rec".equalsIgnoreCase(format)) return "application/vnd.rn-recording";
        if ("mp3".equalsIgnoreCase(format)) return "audio/mpeg";
        if ("wav".equalsIgnoreCase(format)) return "audio/wav";
        return null;
    }
    
}
